package com.testing.class12;

import com.sun.org.apache.xerces.internal.impl.dv.dtd.ENTITYDatatypeValidator;
import com.testing.common.AutoTools;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.swing.text.html.parser.Entity;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @Classname FirstGetDemo
 * @Description 类型说明
 * @Date 2022/10/31 21:19
 * @Created by 特斯汀Roy
 */
public class FirstGetDemo {

    public static String domain="http://localhost:9090/";

    //创建一个默认的httpclient。
    public static CloseableHttpClient client= HttpClients.createDefault();

    public static void main(String[] args) throws IOException {

        /***
         * hello/visit 接口的请求
          */
        //访客用例
        visitGet("?name=roy1","预约访问");
        //匿名用例
        visitGet("","请输入名字");

        //hello/guest/{name} 接口的请求
        //对特殊字符提前进行url编码。
        String encode = URLEncoder.encode("ro y= sd+*&sdf=", "utf-8");
        AutoTools.log.info(encode);
        HttpGet guestGet=new HttpGet(domain+"hello/guest/"+encode);
        String guestResult = EntityUtils.toString(client.execute(guestGet).getEntity(), "utf-8");
        System.out.println(guestResult);
        if (guestResult.equals("欢迎光临 ")){
            AutoTools.log.info("测试成功");
        }else{
            AutoTools.log.error("测试失败");
        }

    }

    public static void visitGet(String param,String expectedResult) throws IOException {
        HttpGet visit=new HttpGet(domain+"hello/visit"+param);
        //发送请求并且获取返回结果
        CloseableHttpResponse visitResp = client.execute(visit);
        AutoTools.log.info(visitResp);
        //从返回结果中获取返回体
        HttpEntity entity = visitResp.getEntity();
        AutoTools.log.info(entity);
        //将返回体解析为字符串。
        String visitResult = EntityUtils.toString(entity,"UTF-8");
        AutoTools.log.info(visitResult);
        //断言
        if(visitResult.contains(expectedResult)){
            AutoTools.log .info("测试通过");
        }else{
            AutoTools.log.error("测试失败");
        }
    }


//    //不提供名字的用例。
//    HttpGet visitNoName=new HttpGet("http://localhost:9090/hello/visit");
//    //发送请求并且获取返回结果
//    CloseableHttpResponse visitNoNameResp = client.execute(visitNoName);
//    //从返回结果中获取返回体
//    HttpEntity noNameentity = visitNoNameResp.getEntity();
//    //将返回体解析为字符串。
//    String visitNoNameResult = EntityUtils.toString(noNameentity,"UTF-8");
//        AutoTools.log.info(visitNoNameResult);
//    //断言
//        if(visitNoNameResult.contains("请输入名字")){
//        AutoTools.log .info("测试通过");
//    }else{
//        AutoTools.log.error("测试失败");
//    }

}
